﻿using System;
using System.IO;
using Common;
using EnvDTE;

namespace SpecFlowTfsLinker.VisualStudioHelper
{
    public class VisualStudioItemHelper
    {
        private readonly SelectedItem _selectedItem;
        private const string VsProjectItemKindPhysicalFolder = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}";

        public VisualStudioItemHelper(SelectedItems selectedItems)
        {
            if (selectedItems.Count == 0)
                throw new Exception(Resource.VS_NO_SELECTED_ITEM);

            _selectedItem = selectedItems.Item(1);
        }

        public ProjectItems GetSelectedProjectItems()
        {
            if (IsProject)
            {
                return _selectedItem.Project.ProjectItems;
            }
            if (IsFolder)
            {
                return _selectedItem.ProjectItem.ProjectItems;
            }
            throw NotSupportedException();
        }

        public string GetPathFromSelectedItem()
        {
            if (IsProject)
            {
                return GetProjectPath();
            }
            if (IsFolder)
            {
                return GetFolderPath();
            }
            throw NotSupportedException();
        }

        private string GetFolderPath()
        {
            return _selectedItem.ProjectItem.FileNames[0];
        }

        private string GetProjectPath()
        {
            return Path.GetDirectoryName(_selectedItem.Project.FullName);
        }

        private bool IsFolder
        {
            get
            {
                return _selectedItem.ProjectItem.Kind == VsProjectItemKindPhysicalFolder;
            }
        }

        private bool IsProject
        {
            get
            {
                return _selectedItem.ProjectItem == null && _selectedItem.Project.Name == _selectedItem.Name;
            }
        }

        private static Exception NotSupportedException()
        {
            return new NotSupportedException(Resource.VS_CAN_ONLY_ADD_ITEM_PROJECT_FOLDER);
        }
    }
}